//
//  LoginViewController.swift
//  globalcarbusiness
//
//  Created by dongzhenyu on 2017/7/3.
//  Copyright © 2017年 dongzhenyu. All rights reserved.
//

import UIKit
import SnapKit

class LoginViewController: UIViewController {

    // MARK: - 内部属性
    fileprivate var username: String = ""
    fileprivate var password: String = ""
    fileprivate var isRememberPassword: Bool = false
    fileprivate let userdefault = UserDefaults.standard
    fileprivate var rememberBtn : UIButton!
    fileprivate lazy var nameSpace: CustonTextField = {
        let name = CustonTextField()
        name.leftView = UIImageView(imageName: "icon_renwu")
        name.keyboardType = UIKeyboardType.default
        name.placeholder = "请输入商家编号"
        name.clearButtonMode = UITextFieldViewMode.whileEditing
        name.delegate = self
        return name
    }()
    
    fileprivate lazy var codeSpace: CustonTextField = {
        let code = CustonTextField()
        code.isSecureTextEntry = true
        code.returnKeyType = UIReturnKeyType.done
        code.placeholder = "请输入密码"
        code.leftView = UIImageView(imageName: "icon_mima")
        code.keyboardType = UIKeyboardType.default
        code.clearButtonMode = UITextFieldViewMode.whileEditing
        code.delegate = self
        return code
    }()
    
    fileprivate lazy var imageView: UIImageView = {
        let imageView = UIImageView(imageName: "denglu")
        return imageView
    }()
    
    fileprivate lazy var loginButton: UIButton = {
    
        let btn = UIButton()
        btn.backgroundColor = UIColor ( red: 0.0, green: 0.7216, blue: 0.9961, alpha: 1.0)
        btn.setTitle("登录", for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
        btn.layer.cornerRadius = 5
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(loginButtonClick), for: .touchUpInside)
        return btn
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        DZYProvider.request(.topicMessage(a:"newlist", c:"data", type:"1")) { (result) in
//            DZYLog(result)
//            
//            switch result {
//                case let .success(response):
//                    DZYLog(response)
//                    do {
//                
//                        
//                    } catch {}
//                
//            case let .failure(error):
//                self.showHUD(.failure, text: error.errorDescription!)
//    
//            }
//            
//        }
        
        view.backgroundColor = UIColor(r: 249, g: 249, b: 249)
        
        setupUI()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
        if let dict = UserDefaults.User.storeValue(forkey: .userInfo) {
            let key = (dict as! NSDictionary).allKeys.first as! String
            nameSpace.text = key
            username = key
           
            if (dict as! NSDictionary)[key] as! String != "" {
                codeSpace.text = (dict as AnyObject)[key]! as? String
                password = ((dict as AnyObject)[key] as? String)!
                isRememberPassword = true
                
                let imageView = rememberBtn.subviews.first as! UIImageView
                imageView.image = UIImage(named: "dagou")
                
            }
        }
    }
}

// MARK: - init code
extension LoginViewController {
    
    fileprivate func setupUI() {
       
        view.addSubview(imageView)
        view.addSubview(nameSpace)
        view.addSubview(codeSpace)
        
        imageView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
           make.height.equalTo(imageView.snp.width).dividedBy(750.0/377)
        }
        
        nameSpace.snp.makeConstraints { (make) in
            make.top.equalTo(imageView.snp.bottom).offset(39 * HEIGHT_SCALE)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        codeSpace.snp.makeConstraints { (make) in
            make.top.equalTo(nameSpace.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        let rememberBtn = setupButton("jizhumima", selector: #selector(rememberBtnClicked))
        view.addSubview(rememberBtn)
        self.rememberBtn = rememberBtn
        rememberBtn.snp.makeConstraints { (make) in
            make.top.equalTo(codeSpace.snp.bottom).offset(7 * HEIGHT_SCALE)
            make.left.equalToSuperview().offset(20)
            make.size.equalTo(CGSize(width:102,height: 30))
        }
        
        let forgetBtn = setupButton("wangjimima", selector: #selector(forgetBtnClick))
        view.addSubview(forgetBtn)
        forgetBtn.snp.makeConstraints { (make) in
            make.top.equalTo(rememberBtn)
            make.size.equalTo(CGSize(width:45,height: 30))
            make.right.equalToSuperview().offset(-20)
        }
        
        view.addSubview(loginButton)
        loginButton.snp.makeConstraints { (make) in
            make.top.equalTo(codeSpace.snp.bottom).offset(64 * HEIGHT_SCALE)
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(44)
        }
        
        let registBtn = setupButton("haimeizhanghao", selector: #selector(registBtnClicked))
        view.addSubview(registBtn)
        registBtn.snp.makeConstraints { (make) in
            make.top.equalTo(loginButton.snp.bottom).offset(13 * HEIGHT_SCALE)
            make.size.equalTo(CGSize(width:110, height:30))
            make.right.equalTo(loginButton)
        }
    }
    
    fileprivate func setupButton(_ imageNamed: String, selector: Selector) -> UIButton {
        
        let normalImageView = UIImageView(imageName: imageNamed)
        let btn = UIButton(type: UIButtonType.system)
        btn.addSubview(normalImageView)
        normalImageView.snp.makeConstraints { (make) in
            make.left.centerX.equalToSuperview()
            make.top.equalToSuperview()
        }
        btn.addTarget(self, action: selector, for: .touchUpInside)
        return btn
    }
    
}

// MARK: - event
extension LoginViewController {

    func loginButtonClick() {
        view.endEditing(true)
        
        if username != "" && password != "" {
            
            for view in view.subviews {
                view.isUserInteractionEnabled = false
            }
            
            UserAccount.login(withUsername: username, password: password, displayViewController: self, complection: { (result) in
               
                for view in self.view.subviews {
                    view.isUserInteractionEnabled = true
                }
                
                if result == "登录成功" {
                    UserAccount.saveAccount(withUsername: self.username, password: self.password, isRememberPassword: self.isRememberPassword)
                } else {
                    self.isRememberPassword = false
                    let imageView = self.rememberBtn.subviews.first as! UIImageView
                    imageView.image = UIImage(named: "jizhumima")
                    
                    if let dict = UserDefaults.User.storeValue(forkey: .userInfo) {
                        let key = (dict as AnyObject).allKeys.first as! String
                        let newDict = [key: ""]
                        UserDefaults.User.store(newDict, forkey: .userInfo)
                        //                    self.userdefault.setValue(newDict, forKey: "userinfo")
                        //                    self.userdefault.synchronize()
                    }

                }
            })
        } else {
            ProgressHUD.showInfo(withStatus: "请输入用户名和密码")
        }
    }
    
    func rememberBtnClicked(_ sender: UIButton) {
    
        isRememberPassword = !isRememberPassword
        if isRememberPassword == true {
            let imageView = sender.subviews.first as! UIImageView
            imageView.image = UIImage(named: "dagou")
        } else {
            let imageView = sender.subviews.first as! UIImageView
            imageView.image = UIImage(named: "jizhumima")
            
            if let dict = UserDefaults.User.storeValue(forkey: .userInfo) {
                let key = (dict as AnyObject).allKeys.first as! String
                let newDict = [key: ""]
                UserDefaults.User.store(newDict, forkey: .userInfo)
//                userdefault.setValue(newDict, forKey: "userinfo")
//                userdefault.synchronize()
            }
        }
    }
    
    func forgetBtnClick() {
        
        let forgetVc = ForgetViewController()
        
        if nameSpace.text != "" {
            forgetVc.tel = nameSpace.text
        }
        present(MyNavigationController(rootViewController: forgetVc), animated: true, completion: nil)
    }
    
    func registBtnClicked() {
        present(MyNavigationController(rootViewController: RegisterViewController()), animated: true, completion: nil)
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        view.endEditing(true)
    }
}

// MARK: - UITextFieldDelegate
extension LoginViewController : UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == nameSpace {
            codeSpace.becomeFirstResponder()
        } else if textField == codeSpace {
            nameSpace.becomeFirstResponder()
        }
        
        return true
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == nameSpace {
            username = textField.text!
        } else if textField == codeSpace {
            password = textField.text!
        }
    }
}
